import React, { Component } from "react";

// 导入connect，用于连接store
import { connect } from "react-redux";

// 导入models
// import models from "@/models/Products";
//导入goods的接口
import modelsGood from "@/models/Goods";

import {
  Cascader,
  Button,
  Form,
  Input,
  InputNumber,
  //   Select,
  Upload,
  Modal,
} from "antd";
// const { Option } = Select;
// import { SearchOutlined } from "@ant-design/icons";
import { PlusOutlined } from "@ant-design/icons";

const layout = {
  labelCol: {
    span: 4,
  },
  wrapperCol: {
    span: 20,
  },
};
/* eslint-disable no-template-curly-in-string */

const validateMessages = {
  required: "${label} is required!",
  types: {
    email: "${label} is not a valid email!",
    number: "${label} is not a valid number!",
  },
  number: {
    range: "${label} must be between ${min} and ${max}",
  },
};

// 图片base64
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}

class ProductAddUpdate extends Component {
  state = {
    showHead: false,
    //   列表数据
    goodList: [],
    //   图片上传
    previewVisible: false,
    previewImage: "",
    previewTitle: "",
    fileList: [
      {
        uid: "-1",
        name: "image.png",
        status: "done",
        url: "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png",
      },
    ],
    residences: [
      {
        value: "zhejiang",
        label: "Zhejiang",
        children: [
          {
            value: "hangzhou",
            label: "Hangzhou",
          },
        ],
      },
      {
        value: "jiangsu",
        label: "Jiangsu",
        children: [
          {
            value: "nanjing",
            label: "Nanjing",
          },
        ],
      },
    ],
  };

  render() {
    // 图片上传
    const { previewVisible, previewImage, fileList, previewTitle } = this.state;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );

    return (
      <div>
        <Button onClick={this.goBack}>返回产品列表</Button>&emsp;
        {this.state.showHead ? "添加商品" : "修改信息"}
        <div style={{ width: "600px", marginTop: "20px" }}>
          <Form
            {...layout}
            name="nest-messages"
            onFinish={this.onFinish}
            validateMessages={validateMessages}
          >
            <Form.Item
              name={["user", "name"]}
              label="商品名称"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name={["user", "desc"]}
              label="商品描述"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input.TextArea />
            </Form.Item>
            <Form.Item
              name={["user", "price"]}
              label="价格"
              rules={[
                {
                  type: "number",
                  min: 0,
                  max: 99999,
                },
              ]}
            >
              <InputNumber />
            </Form.Item>
            <Form.Item
              name="residence"
              label="商品分类"
              rules={[
                {
                  type: "array",
                  required: true,
                  message: "Please select your habitual residence!",
                },
              ]}
            >
              <Cascader
                options={this.state.goodList}
                onChange={this.showSonList}
                onClick={this.aa}
              />
            </Form.Item>

            {/* 图片 */}
            <div style={{ marginLeft: "40px", marginBottom: "5px" }}>
              <Upload
                action="http://120.55.193.14:5000/manage/img/upload"
                listType="picture-card"
                fileList={fileList}
                onPreview={this.handlePreview}
                onChange={this.handleChange}
              >
                {fileList.length >= 8 ? null : uploadButton}
              </Upload>
              <Modal
                visible={previewVisible}
                title={previewTitle}
                footer={null}
                onCancel={this.handleCancel}
              >
                <img
                  alt="example"
                  style={{ width: "100%" }}
                  src={previewImage}
                />
              </Modal>
            </div>

            <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    );
  }
  componentDidMount() {
    if (this.props.match.params.id === "10") {
      this.setState({ showHead: true });
	  }
    // 请求所有的分类
    let parentId = 0;
    let goodList = [];
    modelsGood.goodList(parentId).then((ret) => {
      ret.data.forEach((item) => {
        goodList.push({
          label: item.name,
          value: item._id,
        });
      });
      this.setState(() => {
        return {
          goodList,
        };
      });
    });
  }

  aa = () => {};
  showSonList = (a) => {
    let List = this.state.goodList;
    for (let key in this.state.goodList) {
      let str = this.state.goodList[key].value;
      if (key < 20) {
        modelsGood.goodList(str).then((ret) => {
          List[key].children = ret.data;
        });
      }
    }
    this.setState(
      () => {
        return { goodList: List };
      },
      () => {
      }
    );
  };

  onFinish = (values) => {
  };

  // 图片上传
  // 图片缩小
  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle:
        file.name || file.url.substring(file.url.lastIndexOf("/") + 1),
    });
  };

  handleChange = ({ fileList }) => {
    this.setState({ fileList });
  };

  // 返回products页面
  goBack = () => {
    this.props.history.goBack();
  };
}

export default connect(
  (state) => ({ data: state.productGetDate }),
  {}
)(ProductAddUpdate);
